package com.hy.until;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 安全工具类（JWT版本）
 */
public class SecurityUtils {

    private static final String TOKEN_HEADER = "Authorization";
    private static final String TOKEN_PREFIX = "Bearer ";
    private static final String SECRET_KEY = "your-secret-key"; // 建议使用更安全的密钥
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 获取当前登录用户ID
     */
    public static Integer getUserId() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            
            // 1. 先尝试从请求头获取token
            String token = request.getHeader(TOKEN_HEADER);
            if (token != null && token.startsWith(TOKEN_PREFIX)) {
                token = token.substring(TOKEN_PREFIX.length());
                try {
                    // 尝试解析JWT token
                    Claims claims = parseToken(token);
                    if (claims != null && claims.get("userInfo") != null) {
                        Map<String, Object> userInfo = claims.get("userInfo", Map.class);
                        if (userInfo.containsKey("id")) {
                            return Integer.valueOf(userInfo.get("id").toString());
                        }
                    }
                } catch (Exception e) {
                    // JWT解析失败，继续尝试其他方式
                }
            }

            // 2. 如果token中没有，尝试从session获取userInfo
            Object userInfoObj = request.getSession().getAttribute("userInfo");
            if (userInfoObj != null) {
                if (userInfoObj instanceof Map) {
                    Map<String, Object> userInfo = (Map<String, Object>) userInfoObj;
                    if (userInfo.containsKey("id")) {
                        return Integer.valueOf(userInfo.get("id").toString());
                    }
                }
            }

            // 3. 如果session中没有，尝试从token属性获取
            Object tokenObj = request.getSession().getAttribute("token");
            if (tokenObj != null) {
                if (tokenObj instanceof Map) {
                    Map<String, Object> tokenInfo = (Map<String, Object>) tokenObj;
                    if (tokenInfo.containsKey("id")) {
                        return Integer.valueOf(tokenInfo.get("id").toString());
                    }
                }
            }

            throw new ServiceException("用户未登录");
        } catch (Exception e) {
            throw new ServiceException("用户未登录");
        }
    }

    /**
     * 获取当前登录用户名
     */
    public static String getUsername() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            
            // 1. 先尝试从session获取userInfo
            Object userInfoObj = request.getSession().getAttribute("userInfo");
            if (userInfoObj != null) {
                if (userInfoObj instanceof Map) {
                    Map<String, Object> userInfo = (Map<String, Object>) userInfoObj;
                    if (userInfo.containsKey("username")) {
                        return userInfo.get("username").toString();
                    }
                }
            }

            // 2. 如果没有，尝试从token中获取
            String token = request.getHeader(TOKEN_HEADER);
            if (token != null && token.startsWith(TOKEN_PREFIX)) {
                Claims claims = parseToken(token.substring(TOKEN_PREFIX.length()));
                if (claims != null && claims.get("userInfo") != null) {
                    Map<String, Object> userInfo = claims.get("userInfo", Map.class);
                    if (userInfo.containsKey("username")) {
                        return userInfo.get("username").toString();
                    }
                }
            }

            throw new ServiceException("用户未登录");
        } catch (Exception e) {
            throw new ServiceException("用户未登录");
        }
    }

    /**
     * 获取当前登录用户手机号
     */
    public static String getPhone() {
        try {
            Claims claims = getTokenClaims();
            if (claims != null) {
                Map<String, Object> userInfo = claims.get("userInfo", Map.class);
                if (userInfo != null && userInfo.containsKey("phone")) {
                    return userInfo.get("phone").toString();
                }
            }
        } catch (Exception e) {
            throw new ServiceException("用户未登录");
        }
        throw new ServiceException("用户未登录");
    }

    /**
     * 获取用户头像URL
     */
    public static String getAvatarUrl() {
        try {
            Claims claims = getTokenClaims();
            if (claims != null) {
                Map<String, Object> userInfo = claims.get("userInfo", Map.class);
                if (userInfo != null && userInfo.containsKey("avatarUrl")) {
                    return userInfo.get("avatarUrl").toString();
                }
            }
        } catch (Exception e) {
            return null; // 头像获取失败返回null
        }
        return null;
    }

    /**
     * 判断用户是否已登录
     */
    public static boolean isAuthenticated() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            
            // 检查session中是否有用户信息
            if (request.getSession().getAttribute("userInfo") != null) {
                return true;
            }

            // 检查请求头中是否有有效token
            String token = request.getHeader(TOKEN_HEADER);
            if (token != null && token.startsWith(TOKEN_PREFIX)) {
                Claims claims = parseToken(token.substring(TOKEN_PREFIX.length()));
                return claims != null && claims.get("userInfo") != null;
            }

            return false;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取完整的用户信息
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> getUserInfo() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            
            // 1. 先尝试从session获取
            Object userInfoObj = request.getSession().getAttribute("userInfo");
            if (userInfoObj instanceof Map) {
                return (Map<String, Object>) userInfoObj;
            }

            // 2. 再尝试从token获取
            String token = request.getHeader(TOKEN_HEADER);
            if (token != null && token.startsWith(TOKEN_PREFIX)) {
                Claims claims = parseToken(token.substring(TOKEN_PREFIX.length()));
                if (claims != null && claims.get("userInfo") != null) {
                    return claims.get("userInfo", Map.class);
                }
            }

            throw new ServiceException("用户未登录");
        } catch (Exception e) {
            throw new ServiceException("用户未登录");
        }
    }

    /**
     * 获取Token中的Claims
     */
    private static Claims getTokenClaims() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(TOKEN_HEADER);

        if (token != null && token.startsWith(TOKEN_PREFIX)) {
            token = token.substring(TOKEN_PREFIX.length());
            return parseToken(token);
        }
        return null;
    }

    /**
     * 解析JWT token
     */
    private static Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }
}
